using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

namespace CMS.Web
{
    public class SiteNavigation
    {        
        public static string GetRelativePathToApplicatonRoot(string fullPath)
        {
            string applicationPath = GetApplicationPath();
            if (0 == applicationPath.Length) //application path is root
                return RemoveHeadingSlash(fullPath);

            Match m = Regex.Match(fullPath, "^\\/?" + applicationPath + "(.*)$", RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return RemoveHeadingSlash(m.Groups[1].Value);
            }
            return fullPath;
        }

        private static string GetApplicationPath()
        {
            if (@"/" == HttpContext.Current.Request.ApplicationPath) //root
                return "";
            return HttpContext.Current.Request.ApplicationPath;
        }

        private static string RemoveHeadingSlash(string path)
        {
            if (path.StartsWith(@"/"))
                return path.Substring(1);
            return path;
        }

        public static string RemoveHostFromUrl(string fullPathWithHost)
        {
            Match m = Regex.Match(fullPathWithHost, "^https?:\\/\\/[^\\/]+(.*)$", RegexOptions.IgnoreCase);
            if (m.Success)
            {
                return m.Groups[1].Value;
            }
            return fullPathWithHost;
        }

        public static string GetRootPath()
        {
            string[] strParts = HttpContext.Current.Request.ServerVariables["PATH_INFO"].Split('/');
            string strHttpHost = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_HOST"];
            if (strHttpHost == null || strHttpHost == "")
            {
                strHttpHost = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
            }
            
            return "http://" + strHttpHost + ((HttpContext.Current.Request.ApplicationPath == "/") ? ("/") : (HttpContext.Current.Request.ApplicationPath + "/"));
        }
    }
}
